/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controls;


import com.aptech.bluepumpkin.*;
import com.aptech.bluepumpkin.beans.EventFacade;
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
import utils.Constants;
import utils.SumaryPrize;
import utils.Uility;
import utils.WinnerDetails;

/**
 *
 * @author Chien
 */
@ManagedBean
@SessionScoped
public class EventControl implements Serializable {

    
    @EJB
    private EventFacade eventFacade;
//    @EJB
//    private PrizeFacade prizeFacade;
    private Event selectedevent;
    private Event newEvent = new Event();
    public int MAX_PALYERS = Integer.MAX_VALUE;
    public int MIN_PALYERS = 0;
    private Date currentDate;

    public String decodeString(String text){
        return Uility.decodeString(text);
    }
    public Date getCurrentDate() {
        return currentDate = new Date();
    }

    public void setCurrentDate(Date currentDate) {
        this.currentDate = currentDate;
    }

    public int getMAX_PALYERS() {
        return MAX_PALYERS;
    }

    public void setMAX_PALYERS(int MAX_PALYERS) {
        this.MAX_PALYERS = MAX_PALYERS;
    }

    public int getMIN_PALYERS() {
        return MIN_PALYERS;
    }

    public void setMIN_PALYERS(int MIN_PALYERS) {
        this.MIN_PALYERS = MIN_PALYERS;
    }
    /**
     * upcoming event: event's starting date is greater than current date.
     */
    /**
     * current event: event's starting date is less than current date and
     * event's ending date is not greater than current date
     */
    private List<Event> events;
    private final int SHORT_DESCRIPTION_LENGHT = 150;
    private final int MEDIUM_DESCRIPTION_LENGHT = 500;
    private String uploadFileName = " ";
    private int activeIndex = 0;
    private boolean disableUpdateTab = true;

    public boolean isDisableUpdateTab() {
        return disableUpdateTab;
    }

    public boolean isDisableOthersTab() {
        return !disableUpdateTab;
    }

    public void setDisableUpdateTab(boolean disableUpdateTab) {
        this.disableUpdateTab = disableUpdateTab;
    }

    public int getActiveIndex() {
        return activeIndex;
    }

    public void setActiveIndex(int activeIndex) {
        this.activeIndex = activeIndex;
    }

    public void updateEvent() {
        if (activeIndex == 2) {
            activeIndex = 0;
            disableUpdateTab = true;
        } else {
            activeIndex = 2;
            disableUpdateTab = false;
        }


        System.out.println("Tabviews: ------------activeIndex : " + activeIndex);
    }

    public List<SumaryPrize> selectAllPrizeByEvent() {
        ArrayList<SumaryPrize> sumaryPrizesList = new ArrayList<SumaryPrize>();
        Event event = selectedevent;
        if (null == event) {
            System.out.println("---selectAllPrizeByEvent: event is NULL-----");
            return sumaryPrizesList;
        }
        SumaryPrize sumaryPrize = new SumaryPrize(event);
        // get list<prize> within a month.
        List<Prize> prizeList = event.getPrizeList();
        try {
            // get Registration from prize
            for (Prize prize : prizeList) {

                List<Winner> winnerList = prize.getWinnerList();
                for (Winner winner : winnerList) {
                    Registration registration = winner.getRegistration();
                    // find User by registration
                    Users user = registration.getCreatedBy();
                    // create new WinnerDetails
                    WinnerDetails winnerDetails = new WinnerDetails(user, prize);
                    //create new SumaryPrize

                    // add WinnerDetails into sumaryPrizesList list
                    sumaryPrize.getWinnerList().add(winnerDetails);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return sumaryPrizesList;
    }

    public void redirectToAddEvent() {

        System.out.println("------redirectToEvent------------------");

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/event/addEventPage.xhtml";
        utils.Uility.redirectPage(context, newEvent, path);
    }

    public void redirectToListEvent() {

        System.out.println("------redirectToEvent------------------");

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/event/adminHomePage.xhtml";
        utils.Uility.redirectPage(context, newEvent, path);
    }

    public void redirectToUpdateEvent() {

        System.out.println("------redirectToEvent------------------");

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/event/editEvent.xhtml";
        utils.Uility.redirectPage(context, selectedevent, path);
    }

    public void redirectToEventDetails() {

        System.out.println("------redirectToEvent------------------");

        FacesContext context = FacesContext.getCurrentInstance();
        String path = context.getExternalContext().getRequestContextPath() + "/faces/admin/event/eventDetails.xhtml";
        utils.Uility.redirectPage(context, selectedevent, path);
    }

//    public List<Prize> getAllPrizeByEvent() {
//        if (null != selectedevent) {
//            return selectedevent.getPrizeList();
//        } else {
//            return new ArrayList<Prize>();
//
//        }
//    }
    /**
     * Make short description of event
     *
     * @param event
     * @return string of short description of event
     */
    public String shortEventDescription(Event event) {
        String shortDes = event.getDescription();
        if (null != shortDes) {
            if (shortDes.length() > SHORT_DESCRIPTION_LENGHT) {
                shortDes = shortDes.substring(0, SHORT_DESCRIPTION_LENGHT) + "...";
            }
        }
        return shortDes;
    }

    public String mediumEventDescription(Event event) {
        String shortDes = event.getDescription();
        if (null != shortDes) {
            if (shortDes.length() > MEDIUM_DESCRIPTION_LENGHT) {
                shortDes = shortDes.substring(0, MEDIUM_DESCRIPTION_LENGHT) + "...";
            }
        }
        return shortDes;
    }

    /**
     * current event: event's starting date is less than current date and
     * event's ending date is not greater than current date
     *
     * @return List<Event>
     */
    public List<Event> getCurrentEventList() {
        return eventFacade.getCurrentEvents();
    }

    public List<Event> pastEvents() {
        return eventFacade.getPastEvents();
    }

    /**
     * upcoming event: event's starting date is greater than current date.
     *
     * @return List<Event>
     */
    public List<Event> getUpcomingEventList() {
        return eventFacade.getUpcomingEvents();
    }

    public Event getSelectedevent() {
        return selectedevent;
    }

    public void setSelectedevent(Event selectedevent) {
        this.selectedevent = selectedevent;
    }

    public Event getNewEvent() {
        return newEvent;
    }

    public void setNewEvent(Event newEvent) {
        this.newEvent = newEvent;
    }

    /**
     * Creates a new instance of EventControl
     */
    public EventControl() {
        selectedevent = new Event();

    }

    /**
     * Get all events (active and not active)
     *
     * @return List<Event>
     */
    public List<Event> getAllEvent() {
        events = eventFacade.getAllEvents();
        return events;
    }

    public List<Event> getAllActiveEvents() {
        return eventFacade.getAllActiveEvents();
    }

    public void handleFileUploadAddEvent(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    uploadFileName = Constants.DATABASE_IMAGE_PATH + time + ext;
                    newEvent.setPhoto(uploadFileName);
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + uploadFileName);

                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }

    public void handleFileUploadEditEvent(FileUploadEvent event) {
        if (null != event.getFile()) {

            try {

                File fileio;
                UploadedFile fileUploaded = event.getFile();
                long time = System.currentTimeMillis();

                String fileName = fileUploaded.getFileName();
                if (null != fileName && fileName.length() > 0) {
                    int lastIndexOf = fileName.lastIndexOf(".");
                    String ext = fileName.substring(lastIndexOf);
                    // fileUploaded name on disk
                    String realFileName = Constants.UPLOAD_PATH + time + ext;
                    // fileUploaded name store in database ex: /uploads/xxxx.jpg
                    uploadFileName = Constants.DATABASE_IMAGE_PATH + time + ext;
                    selectedevent.setPhoto(uploadFileName);
                    fileio = new File(realFileName);
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(fileio));
                    bos.write(fileUploaded.getContents());

                    bos.flush();
                    bos.close();
                    System.out.println("--- file uploaded " + uploadFileName);
                }
            } catch (IOException ex) {

                Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            System.out.println("---No file upload ");
        }


    }

    public void insert() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();

            /**
             * Validate dates
             */
            if (newEvent.getStartDate().after(newEvent.getEndDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "End Date MUST BE GREATER THAN Start Date", ""));
                return;
            }
            if (newEvent.getStartRegDate().after(newEvent.getStartDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "StartRegDate MUST BE LESS THAN Start Date", ""));
                return;
            }
            if (newEvent.getEndRegDate().before(newEvent.getStartRegDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "EndRegDate MUST BE GREATER THAN StartRegDate", ""));
                return;
            }
            eventFacade.create(newEvent);
            newEvent = new Event();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Create Success", ""));

        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Insert failed", ""));
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void edit() {
        FacesContext context = FacesContext.getCurrentInstance();
        try {
            /**
             * Validate dates
             */
            if (selectedevent.getStartDate().after(selectedevent.getEndDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "End Date MUST BE GREATER THAN Start Date", ""));
                return;
            }
            if (selectedevent.getStartRegDate().after(selectedevent.getStartDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "StartRegDate MUST BE LESS THAN Start Date", ""));
                return;
            }
            if (selectedevent.getEndRegDate().before(selectedevent.getStartRegDate())) {
                context.addMessage(context.getViewRoot().getClientId(), new FacesMessage(FacesMessage.SEVERITY_ERROR, "EndRegDate MUST BE GREATER THAN StartRegDate", ""));
                return;
            }
            eventFacade.edit(selectedevent);
            selectedevent = new Event();
            // update tabs

            redirectToListEvent();
            System.out.println("-------Edited--------------------");

        } catch (Exception ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public void delete(Event event) {

       
        try {
            eventFacade.remove(event);

            redirectToListEvent();


        } catch (Exception ex) {
            Logger.getLogger(EventControl.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

  
    public String getUploadFileName() {
        return uploadFileName;
    }

    public void setUploadFileName(String uploadFileName) {
        this.uploadFileName = uploadFileName;
    }

    public void resetEventForm() {
//       newEvent.setTitle("");
//       newEvent.setActive(true);
//       newEvent.setDescription("");
//       newEvent.setEndDate(null);
//       newEvent.setEndRegDate(null);
//       newEvent.setPhoto("");
//       newEvent.setStartRegDate(null);
//       newEvent.setStartDate(new Date());
        setNewEvent(new Event());
//        FacesContext.getCurrentInstance().getPartialViewContext().setRenderAll(true);

        System.out.println("----------- reseted------------");

    }
}
